package algorithm.search;

/**
 * @Author: 李浩然
 * @Date: 2020/12/28 1:12 下午
 */
public class BinarySearch {
    public static int BinarySearchCur(int[] num, int left, int right, int target) {
        if (num.length == 0 || num == null) return -1;
        int mid = left + (right - left) / 2;
        if (num[mid] == target) return mid;
        else if (num[mid] > target) {
            return BinarySearchCur(num, left, mid - 1, target);
        } else return BinarySearchCur(num, mid + 1, right, target);
    }

    public static int BinarySearchWhile(int[] arr, int left, int right, int target) {
        if (arr == null || arr.length == 0) return -1;
        if (left > right) return -1;
        int mid;
        while (left <= right) {
            mid = left + (right - left) / 2;
            if (arr[mid] == target) return mid;
            else if (arr[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 5, 4, 2};
        int num = BinarySearchCur(arr, 0, arr.length - 1, 5);
        int num2 = BinarySearchWhile(arr, 0, arr.length - 1, 5);
        System.out.println(num);
        System.out.println(num2);
    }
}
